﻿
using System;
using System.IO;
using System.Text;

namespace Stanza.MSBuild.Tasks
{
    public static class PathTools
    {
        const UInt32 FILE_ATTRIBUTE_DIRECTORY = 0x10;
        const Int32 MAX_PATH = 260;

        [System.Runtime.InteropServices.DllImport( "shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto )]
        static extern bool PathRelativePathTo(
             [System.Runtime.InteropServices.Out] StringBuilder pszPath,
             [System.Runtime.InteropServices.In] string pszFrom,
             [System.Runtime.InteropServices.In] uint dwAttrFrom,
             [System.Runtime.InteropServices.In] string pszTo,
             [System.Runtime.InteropServices.In] uint dwAttrTo
        );

        // Return a relative path from the source path to the file
        public static string GetRelativePath( string srcPath, string fileName )
        {
            StringBuilder relativePath = new StringBuilder( MAX_PATH );
            if( PathRelativePathTo( relativePath,
                                    Path.GetFullPath( srcPath ), FILE_ATTRIBUTE_DIRECTORY,
                                    Path.GetFullPath( fileName ), 0 ) )
                return ( ( relativePath[0] == '.' ) && ( relativePath[1] == '\\' ) )
                            ? relativePath.ToString( 2, relativePath.Length - 2 )
                            : relativePath.ToString();
            return fileName;
        }
    }
}
